using System;
using System.Drawing;
using System.Windows.Forms;
using GomokuGame.AI;

namespace GomokuGame
{
    public partial class Form1 : Form
    {
        private GameEngine gameEngine;
        private System.Windows.Forms.Timer aiProgressTimer;

        public Form1()
        {
            InitializeComponent();
            InitializeGame();
            InitializeAITimer();
        }

        /// <summary>
        /// 初始化游戏
        /// </summary>
        private void InitializeGame()
        {
            gameEngine = new GameEngine();
            boardControl.SetGameEngine(gameEngine);

            // 绑定事件
            gameEngine.GameStarted += OnGameStarted;
            gameEngine.GameEnded += OnGameEnded;
            gameEngine.PlayerChanged += OnPlayerChanged;
            gameEngine.PiecePlaced += OnPiecePlaced;
            gameEngine.AIThinkingProgressChanged += OnAIThinkingProgressChanged;
            gameEngine.AIMoveCompleted += OnAIMoveCompleted;

            UpdateUI();
        }

        /// <summary>
        /// 初始化AI进度定时器
        /// </summary>
        private void InitializeAITimer()
        {
            aiProgressTimer = new System.Windows.Forms.Timer();
            aiProgressTimer.Interval = 100; // 100ms更新一次
            aiProgressTimer.Tick += AiProgressTimer_Tick;
        }

        /// <summary>
        /// 更新界面
        /// </summary>
        private void UpdateUI()
        {
            if (gameEngine == null) return;

            // 更新当前玩家显示
            string playerText = gameEngine.CurrentPlayer == PieceType.Black ? "黑" : "白";
            lblCurrentPlayer.Text = $"当前玩家：{playerText}";

            // 更新游戏状态显示
            string stateText = GetGameStateText(gameEngine.CurrentState);
            lblGameState.Text = $"状态：{stateText}";

            // 更新步数显示
            lblMoveCount.Text = $"步数：{gameEngine.MoveHistory.Count}";

            // 更新AI信息显示
            UpdateAIInfo();

            // 更新按钮状态
            btnUndo.Enabled = gameEngine.CurrentState == GameState.Playing && 
                             gameEngine.MoveHistory.Count > 0 && 
                             gameEngine.CurrentUndoCount < gameEngine.MaxUndoCount;
            btnRestart.Enabled = gameEngine.CurrentState != GameState.NotStarted;

            // 重绘棋盘
            boardControl.Invalidate();
        }

        /// <summary>
        /// 更新AI信息显示
        /// </summary>
        private void UpdateAIInfo()
        {
            if (gameEngine.GameMode == GameMode.HumanVsAI || gameEngine.GameMode == GameMode.AIVsAI)
            {
                string aiInfo = $"AI难度：{AIFactory.GetDifficultyName(gameEngine.GetAIDifficulty())}\n";
                aiInfo += $"AI执子：{(gameEngine.GetAIPlayer() == PieceType.Black ? "黑" : "白")}";
                
                if (gameEngine.IsAITurn())
                {
                    aiInfo += "\nAI思考中...";
                }
                
                // 这里可以添加一个标签来显示AI信息
                // lblAIInfo.Text = aiInfo;
            }
        }

        /// <summary>
        /// 获取游戏状态文本
        /// </summary>
        /// <param name="state">游戏状态</param>
        /// <returns>状态文本</returns>
        private string GetGameStateText(GameState state)
        {
            switch (state)
            {
                case GameState.NotStarted:
                    return "未开始";
                case GameState.Playing:
                    return "进行中";
                case GameState.BlackWin:
                    return "黑方胜利";
                case GameState.WhiteWin:
                    return "白方胜利";
                case GameState.Draw:
                    return "平局";
                case GameState.Paused:
                    return "暂停";
                default:
                    return "未知";
            }
        }

        /// <summary>
        /// 棋盘点击事件处理
        /// </summary>
        /// <param name="sender">事件源</param>
        /// <param name="e">事件参数</param>
        private void boardControl_BoardClick(object sender, BoardClickEventArgs e)
        {
            if (gameEngine == null || gameEngine.CurrentState != GameState.Playing) return;

            // 尝试落子
            bool success = gameEngine.PlacePiece(e.Row, e.Col);
            if (success)
            {
                UpdateUI();
            }
        }

        /// <summary>
        /// 游戏开始事件处理
        /// </summary>
        /// <param name="sender">事件源</param>
        /// <param name="e">事件参数</param>
        private void OnGameStarted(object sender, GameEventArgs e)
        {
            if (InvokeRequired)
            {
                Invoke(new Action(() => OnGameStarted(sender, e)));
                return;
            }

            UpdateUI();
        }

        /// <summary>
        /// 游戏结束事件处理
        /// </summary>
        /// <param name="sender">事件源</param>
        /// <param name="e">事件参数</param>
        private void OnGameEnded(object sender, GameEventArgs e)
        {
            if (InvokeRequired)
            {
                Invoke(new Action(() => OnGameEnded(sender, e)));
                return;
            }

            UpdateUI();

            // 显示游戏结果
            string message = GetGameResultMessage(e.GameState);
            MessageBox.Show(message, "游戏结束", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        /// <summary>
        /// 玩家切换事件处理
        /// </summary>
        /// <param name="sender">事件源</param>
        /// <param name="e">事件参数</param>
        private void OnPlayerChanged(object sender, PlayerChangedEventArgs e)
        {
            if (InvokeRequired)
            {
                Invoke(new Action(() => OnPlayerChanged(sender, e)));
                return;
            }

            UpdateUI();
        }

        /// <summary>
        /// 棋子落子事件处理
        /// </summary>
        /// <param name="sender">事件源</param>
        /// <param name="e">事件参数</param>
        private void OnPiecePlaced(object sender, MoveEventArgs e)
        {
            if (InvokeRequired)
            {
                Invoke(new Action(() => OnPiecePlaced(sender, e)));
                return;
            }

            UpdateUI();
        }

        /// <summary>
        /// AI思考进度变化事件处理
        /// </summary>
        /// <param name="sender">事件源</param>
        /// <param name="e">事件参数</param>
        private void OnAIThinkingProgressChanged(object sender, AIThinkingProgressEventArgs e)
        {
            if (InvokeRequired)
            {
                Invoke(new Action(() => OnAIThinkingProgressChanged(sender, e)));
                return;
            }

            // 更新AI思考进度显示
            UpdateAIThinkingProgress(e.Progress);
        }

        /// <summary>
        /// AI移动完成事件处理
        /// </summary>
        /// <param name="sender">事件源</param>
        /// <param name="e">事件参数</param>
        private void OnAIMoveCompleted(object sender, AIMoveCompletedEventArgs e)
        {
            if (InvokeRequired)
            {
                Invoke(new Action(() => OnAIMoveCompleted(sender, e)));
                return;
            }

            // 停止AI进度定时器
            aiProgressTimer.Stop();
            
            // 更新界面
            UpdateUI();
        }

        /// <summary>
        /// AI进度定时器事件处理
        /// </summary>
        /// <param name="sender">事件源</param>
        /// <param name="e">事件参数</param>
        private void AiProgressTimer_Tick(object sender, EventArgs e)
        {
            if (gameEngine != null && gameEngine.IsAITurn())
            {
                var aiManager = gameEngine.GetAIManager();
                if (aiManager != null && aiManager.CurrentAI != null)
                {
                    int progress = aiManager.CurrentAI.GetThinkingProgress();
                    UpdateAIThinkingProgress(progress);
                }
            }
        }

        /// <summary>
        /// 更新AI思考进度显示
        /// </summary>
        /// <param name="progress">进度百分比</param>
        private void UpdateAIThinkingProgress(int progress)
        {
            // 这里可以更新进度条或状态文本
            // 例如：progressBarAI.Value = progress;
            // 或者：lblAIStatus.Text = $"AI思考中... {progress}%";
        }

        /// <summary>
        /// 获取游戏结果消息
        /// </summary>
        /// <param name="state">游戏状态</param>
        /// <returns>结果消息</returns>
        private string GetGameResultMessage(GameState state)
        {
            switch (state)
            {
                case GameState.BlackWin:
                    return "恭喜！黑方获得胜利！";
                case GameState.WhiteWin:
                    return "恭喜！白方获得胜利！";
                case GameState.Draw:
                    return "游戏结束，双方平局！";
                default:
                    return "游戏结束";
            }
        }

        #region 按钮事件处理

        /// <summary>
        /// 新游戏按钮点击事件
        /// </summary>
        /// <param name="sender">事件源</param>
        /// <param name="e">事件参数</param>
        private void btnNewGame_Click(object sender, EventArgs e)
        {
            ShowNewGameDialog();
        }

        /// <summary>
        /// 悔棋按钮点击事件
        /// </summary>
        /// <param name="sender">事件源</param>
        /// <param name="e">事件参数</param>
        private void btnUndo_Click(object sender, EventArgs e)
        {
            if (gameEngine != null)
            {
                bool success = gameEngine.Undo();
                if (success)
                {
                    UpdateUI();
                }
                else
                {
                    MessageBox.Show("无法悔棋！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
        }

        /// <summary>
        /// 重新开始按钮点击事件
        /// </summary>
        /// <param name="sender">事件源</param>
        /// <param name="e">事件参数</param>
        private void btnRestart_Click(object sender, EventArgs e)
        {
            if (gameEngine != null)
            {
                gameEngine.Restart();
                UpdateUI();
            }
        }

        #endregion

        #region 菜单事件处理

        /// <summary>
        /// 人人对战菜单点击事件
        /// </summary>
        /// <param name="sender">事件源</param>
        /// <param name="e">事件参数</param>
        private void menuHumanVsHuman_Click(object sender, EventArgs e)
        {
            StartNewGame(GameMode.HumanVsHuman);
        }

        /// <summary>
        /// 人机对战菜单点击事件
        /// </summary>
        /// <param name="sender">事件源</param>
        /// <param name="e">事件参数</param>
        private void menuHumanVsAI_Click(object sender, EventArgs e)
        {
            StartNewGame(GameMode.HumanVsAI);
        }

        /// <summary>
        /// 自动演示菜单点击事件
        /// </summary>
        /// <param name="sender">事件源</param>
        /// <param name="e">事件参数</param>
        private void menuAIVsAI_Click(object sender, EventArgs e)
        {
            StartNewGame(GameMode.AIVsAI);
        }

        /// <summary>
        /// 悔棋菜单点击事件
        /// </summary>
        /// <param name="sender">事件源</param>
        /// <param name="e">事件参数</param>
        private void menuUndo_Click(object sender, EventArgs e)
        {
            btnUndo_Click(sender, e);
        }

        /// <summary>
        /// 重新开始菜单点击事件
        /// </summary>
        /// <param name="sender">事件源</param>
        /// <param name="e">事件参数</param>
        private void menuRestart_Click(object sender, EventArgs e)
        {
            btnRestart_Click(sender, e);
        }

        /// <summary>
        /// 退出菜单点击事件
        /// </summary>
        /// <param name="sender">事件源</param>
        /// <param name="e">事件参数</param>
        private void menuExit_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        /// <summary>
        /// 关于菜单点击事件
        /// </summary>
        /// <param name="sender">事件源</param>
        /// <param name="e">事件参数</param>
        private void menuAbout_Click(object sender, EventArgs e)
        {
            MessageBox.Show("五子棋游戏 v1.0\n\n基于需求文档开发\n支持人人对战、人机对战、自动演示等模式", 
                "关于", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        #endregion

        /// <summary>
        /// 显示新游戏对话框
        /// </summary>
        private void ShowNewGameDialog()
        {
            using (var dialog = new GameModeDialog())
            {
                if (dialog.ShowDialog() == DialogResult.OK)
                {
                    switch (dialog.SelectedGameMode)
                    {
                        case GameMode.HumanVsHuman:
                            StartNewGame(GameMode.HumanVsHuman);
                            break;
                        case GameMode.HumanVsAI:
                            ShowHumanVsAIDialog();
                            break;
                        case GameMode.AIVsAI:
                            ShowAIVsAIDialog();
                            break;
                    }
                }
            }
        }

        /// <summary>
        /// 显示人机对战设置对话框
        /// </summary>
        private void ShowHumanVsAIDialog()
        {
            AIDifficulty difficulty = AIDifficulty.Intermediate;
            PieceType aiColor = PieceType.White;

            // 选择AI难度
            using (var difficultyDialog = new AIDifficultyDialog())
            {
                if (difficultyDialog.ShowDialog() == DialogResult.OK)
                {
                    difficulty = difficultyDialog.SelectedDifficulty;
                }
                else
                {
                    return; // 用户取消
                }
            }

            // 选择AI执子颜色
            using (var colorDialog = new AIColorDialog())
            {
                if (colorDialog.ShowDialog() == DialogResult.OK)
                {
                    aiColor = colorDialog.SelectedAIColor;
                }
                else
                {
                    return; // 用户取消
                }
            }

            StartNewGame(GameMode.HumanVsAI, difficulty, aiColor);
        }

        /// <summary>
        /// 显示AI对战设置对话框
        /// </summary>
        private void ShowAIVsAIDialog()
        {
            // 选择AI难度
            using (var difficultyDialog = new AIDifficultyDialog())
            {
                if (difficultyDialog.ShowDialog() == DialogResult.OK)
                {
                    StartNewGame(GameMode.AIVsAI, difficultyDialog.SelectedDifficulty, PieceType.White);
                }
            }
        }

        /// <summary>
        /// 开始新游戏
        /// </summary>
        /// <param name="mode">游戏模式</param>
        private void StartNewGame(GameMode mode)
        {
            StartNewGame(mode, AIDifficulty.Intermediate, PieceType.White);
        }

        /// <summary>
        /// 开始新游戏（带AI参数）
        /// </summary>
        /// <param name="mode">游戏模式</param>
        /// <param name="aiDifficulty">AI难度</param>
        /// <param name="aiPlayer">AI执子颜色</param>
        private void StartNewGame(GameMode mode, AIDifficulty aiDifficulty, PieceType aiPlayer)
        {
            if (gameEngine != null)
            {
                gameEngine.StartNewGame(mode, aiDifficulty, aiPlayer);
                UpdateUI();
            }
        }
        
        #region 游戏记录相关方法
        
        /// <summary>
        /// 获取游戏引擎
        /// </summary>
        /// <returns>游戏引擎</returns>
        public GameEngine GetGameEngine()
        {
            return gameEngine;
        }
        
        /// <summary>
        /// 保存对局菜单点击事件
        /// </summary>
        private void menuSaveGame_Click(object sender, EventArgs e)
        {
            try
            {
                string filePath = gameEngine.SaveGameRecord();
                MessageBox.Show($"游戏记录已保存到：\n{filePath}", "保存成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"保存游戏记录失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        
        /// <summary>
        /// 游戏回放菜单点击事件
        /// </summary>
        private void menuReplay_Click(object sender, EventArgs e)
        {
            var replayForm = new ReplayForm(this);
            replayForm.ShowDialog();
        }
        
        /// <summary>
        /// 导出SGF菜单点击事件
        /// </summary>
        private void menuExportSGF_Click(object sender, EventArgs e)
        {
            try
            {
                using (var saveDialog = new SaveFileDialog())
                {
                    saveDialog.Filter = "SGF文件 (*.sgf)|*.sgf|所有文件 (*.*)|*.*";
                    saveDialog.FileName = $"Gomoku_{DateTime.Now:yyyyMMdd_HHmmss}.sgf";
                    
                    if (saveDialog.ShowDialog() == DialogResult.OK)
                    {
                        string sgfContent = gameEngine.ExportToSGF(saveDialog.FileName);
                        MessageBox.Show("SGF文件导出成功！", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"导出SGF失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        
        #endregion
        
        #region 设置相关方法
        
        /// <summary>
        /// 设置菜单点击事件
        /// </summary>
        private void menuSettings_Click(object sender, EventArgs e)
        {
            try
            {
                var settingsForm = new SettingsForm();
                if (settingsForm.ShowDialog() == DialogResult.OK)
                {
                    // 应用设置到游戏引擎和界面
                    ApplySettings();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"打开设置失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        
        /// <summary>
        /// 应用设置到游戏引擎和界面
        /// </summary>
        private void ApplySettings()
        {
            try
            {
                var settings = GameSettings.Instance;
                
                // 应用窗口设置
                if (settings.WindowMaximized)
                {
                    this.WindowState = FormWindowState.Maximized;
                }
                else
                {
                    this.Size = new Size(settings.WindowWidth, settings.WindowHeight);
                }
                
                // 应用悔棋次数设置
                if (gameEngine != null)
                {
                    gameEngine.MaxUndoCount = settings.MaxUndoCount;
                }
                
                // 应用AI设置
                if (gameEngine != null && gameEngine.GetAIManager() != null)
                {
                    var aiManager = gameEngine.GetAIManager();
                    aiManager.SetAIDifficulty(settings.DefaultAIDifficulty);
                    aiManager.SetTimeLimit(settings.AITimeLimit);
                    aiManager.SetSearchDepth(settings.AISearchDepth);
                }
                
                // 应用界面设置到棋盘控件
                if (boardControl != null)
                {
                    boardControl.ApplySettings(settings);
                }
                
                MessageBox.Show("设置已应用！", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"应用设置失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        
        #endregion
    }
} 